$(function () {
    getUserInfo()

    $('#log_out').on('click', function () {
        // 提示用户是否确认退出
        layer.confirm('确定退出登录?', { icon: 3, title: '提示' }, function (index) {
            localStorage.removeItem('token')
            location.href = '/login.html'
            //关闭确认框
            layer.close(index)
        })
    })
})

function getUserInfo() {
    $.ajax({
        method: 'GET',
        url: '/my/userinfo',
        headers: {
            Authorization: localStorage.getItem('token'),
        },
        success: function (res) {
            if (res.status !== 0) {
                return layui.layer.msg('获取用户信息失败！')

            }

            renderAvatar(res.data);
        },
        error: function () { },
        complete: function (res) {
            console.log(res);
            const {responseJSON:{message,status}
                
            }=res
          if (res.responseJSON.status === 1 && res.responseJSON.message === '身份认证失败！') {
             localStorage.removeItem('token')
            location.href = '/login.html'
            }
          }
    })
}


function renderAvatar(data) {
    const name = data.nicename || data.username
    $('#welcome').html(`欢迎${name}`)
    if (data.user_pic) {
        $('.layui-nav-img').attr('src', data.user_pic).show()
        $('.text-avatar').hide()

    } else {
        const firstName = name[0].toUpperCase()
        $('.text-avatar').html(firstName).show()
        $('.layui-nav-img').hide()
    }
}